
package com.kugou.game.sdk.core;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;

import com.kugou.download.DownloadFile;
import com.kugou.download.FileDownloader;
import com.kugou.download.IProgressListener;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.KGPayInfo;
import com.kugou.game.sdk.api.common.OnPlatformEventListener;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.download.DownloadOperator;
import com.kugou.game.sdk.download.DownloadService;
import com.kugou.game.sdk.download.DownloadServiceUtil;
import com.kugou.game.sdk.download.DownloadServiceUtil.DownloadServiceToken;
import com.kugou.game.sdk.download.DownloadServiceUtil.OnDownloadServiceConnectionListener;
import com.kugou.game.sdk.hotfix.HotFixHelper;
import com.kugou.game.sdk.statistics.StatGameCenterDownloadTask;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.activity.GameCenterActivity;
import com.kugou.game.sdk.ui.activity.GameForumActivity;
import com.kugou.game.sdk.ui.activity.GiftBagActivity;
import com.kugou.game.sdk.ui.activity.LoginActivity;
import com.kugou.game.sdk.ui.activity.RechargeActivity;
import com.kugou.game.sdk.ui.activity.RegisterByPhoneActivity;
import com.kugou.game.sdk.ui.activity.UserCenterActivity;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.DownloadHelper;
import com.kugou.game.sdk.utils.FileType;
import com.kugou.game.sdk.utils.InstallHelper;
import com.kugou.game.sdk.utils.InstallHelper.OnInstallStateListener;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.UrlWrapper;

/**
 * 描述:全局性SDK操作类，内部代码可以从这个类很方便获取到context，配置参数（静态+动态），起到串连外部api类和内部实现类的作用，
 * 为两边提供调用函数
 * 
 * @author chenys
 * @since 2014-12-12 下午5:18:38
 */
public class SDKControler {

    public static final String KUGOU_SDK_TAG = "kugou_sdk";

    private static Context mContext;

    private static BaseSDKConfig mSDKConfig;

    private static int mSdkVersionCode;

    private static String mSdkVersionName;

    private static OnPlatformEventListener mOnPlatformEventListener;

    private static DownloadServiceToken mDownloadServiceToken;

    private static boolean mInitialize;

    private static int mActivityCounter;

    // 支付时的参数，每次支付都需要更新
    private static KGPayInfo mKGPayInfo;

    private static int mServerId = -1;

    private static boolean mIsDebugMode = true;

    public static void init(Context context, BaseSDKConfig sdkConfig, int sdkVersionCode,
            String sdkVersionName, OnPlatformEventListener eventListener) {
        if (context == null) {
            throw new RuntimeException("context can't be null.");
        }

        if (sdkConfig == null) {
            throw new RuntimeException("sdkConfig can't be null.");
        }

        if (eventListener == null) {
            throw new RuntimeException("eventListener can't be null.");
        }

        mContext = context.getApplicationContext();
        mSDKConfig = sdkConfig;
        mSdkVersionCode = sdkVersionCode;
        mSdkVersionName = sdkVersionName;
        mOnPlatformEventListener = eventListener;

        mInitialize = checkConfigCorrect();

        if (!mInitialize) {
            throw new RuntimeException("sdk初始化失败.");
        }

        Rx.init(mContext);

        // 获取res/raw/channel文件的渠道id
        int id = getChannelIdFromRaw();
        mSDKConfig.setChannelId(id);
        Log.d("dax", "channelid-->" + id);

        String currentProcessName = AppUtil.getCurrentProcessName(context);
        if ("com.kugou.game.sdk.pushservice".equals(currentProcessName)) {
            return;
        }
        if ("com.kugou.sdk.bdlocation".equals(currentProcessName)) {
            return;
        }

        // 初始化文件目录
        FolderManager.initSystemFolder();
        InstallHelper.getInstance().init(mContext);
        // 监听APP安装/卸载状态的改变
        InstallHelper.getInstance().setOnInstallStateListener(mOnInstallStateListener);
        // 绑定下载服务
        mDownloadServiceToken = DownloadServiceUtil.bindToService(mContext, mOnConnectionListener);

        // 发送启动统计
        sendInitStatics(sdkConfig);
    }

    // 当次是否发送过启动统计
    private static boolean mInitStatics = false;

    private static synchronized void sendInitStatics(BaseSDKConfig sdkConfig) {
        if (!mInitStatics) {
            StaticsManager.sendAppStartStatics();
            Log.d(KUGOU_SDK_TAG,
                    ">>>>>>>>>>>>>调用初始化SDK接口 merchantId = " + sdkConfig.getMerchantId()
                            + ", appId = " + sdkConfig.getAppId() + ", gameId = "
                            + sdkConfig.getGameId());
            mInitStatics = true;
        }
    }

    /** 获取SDK配置的横竖屏 */
    public static int getOritention() {
        return mSDKConfig != null ? mSDKConfig.getActivityOrientation()
                : ActivityOrientation.LANDSCAPE;
    }

    private static int getChannelIdFromRaw() {
        InputStream is = null;
        BufferedReader br = null;
        try {
            Resources res = mContext.getResources();
            is = res.openRawResource(Rx.raw.channel);
            br = new BufferedReader(new InputStreamReader(is));
            ArrayList<String> data = new ArrayList<String>();
            String line = null;
            while ((line = br.readLine()) != null) {
                if (TextUtils.isEmpty(line)) {// 去除空行（回车）
                    continue;
                }
                data.add(line);
            }
            int size = data.size();
            if (size != 1) {// 多行数据或没有填写数据
                Log.e("configcheck", "!!!Kugou SDK res/raw/channel文件填写有误!!!");
                return 0;
            }
            int channelId = Integer.parseInt(data.get(0));
            return channelId;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (Exception e2) {
            }
        }
    }

    private static boolean checkConfigCorrect() {
        if (getMerchantId() == 0) {
            Log.e("configcheck", "配置信息merchatid不能为空或0");
            return false;
        }
        if (getAppId() == 0) {
            Log.e("configcheck", "配置信息appid不能为空或0");
            return false;
        }
        if (TextUtils.isEmpty(getAppKey())) {
            Log.e("configcheck", "配置信息appkey不能为空或填写错误");
            return false;
        }
        if (TextUtils.isEmpty(getCode())) {
            Log.e("configcheck", "配置信息Code不能为空或填写错误");
            return false;
        }
        if (getGameId() == 0) {
            Log.e("configcheck", "配置信息gameid不能为空或0");
            return false;
        }

        return true;
    }

    private static OnDownloadServiceConnectionListener mOnConnectionListener = new OnDownloadServiceConnectionListener() {

        @Override
        public void onDownloadServiceConnection() {
            DownloadServiceUtil.setGolbalListener(mGlobalDownloadListener);

            HotFixHelper.checkPatchInfo();
        }
    };

    // 全局安装/卸载状态监听
    private static OnInstallStateListener mOnInstallStateListener = new OnInstallStateListener() {

        @Override
        public void onStart(String filePath, String packageName, int versionCode) {
            Intent intent = InstallHelper.createInstallIntent(
                    SDKActions.ACTION_INSTALL_STATE_CHANGED, InstallHelper.STATE_INSTALL_START,
                    packageName, versionCode, filePath);
            mContext.sendBroadcast(intent);
        }

        @Override
        public void onSuccess(String filePath, String packageName, int versionCode) {
            Intent intent = InstallHelper.createInstallIntent(
                    SDKActions.ACTION_INSTALL_STATE_CHANGED, InstallHelper.STATE_INSTALL_SUCCESS,
                    packageName, versionCode, filePath);
            mContext.sendBroadcast(intent);
        }

        @Override
        public void onFaile(String filePath, String packageName, int versionCode, int faileType) {
            Intent intent = InstallHelper.createInstallIntent(
                    SDKActions.ACTION_INSTALL_STATE_CHANGED, InstallHelper.STATE_INSTALL_FAILE,
                    packageName, versionCode, filePath);
            mContext.sendBroadcast(intent);

        }
    };

    /**
     * 全局下载进度状态监听
     */
    private static IProgressListener mGlobalDownloadListener = new IProgressListener() {

        @Override
        public void onProgressChanged(DownloadFile file, int state) {
            String key = file.getKey();
            int classId = file.getClassId();
            String mid = AppUtil.getKugouMID(mContext);
            String uuid = AppUtil.getKugouUUID(mContext);
            User user = UserManager.getInstance().getCurrentUserInternal();
            String kugouid = (user != null ? user.getKugouid() : "0");
            String kugouToken = (user != null ? user.getKugouToken() : "");
            long clientAppid = getAppId();
            String statParams = file.getExt10();
            if (classId == FileType.TYPE_APP_FILE) {
                if (state == FileDownloader.FINISH) {

                    // 发送H5游戏中心 下载完成统计
                    if (file.isNewDownload()) {// 中间无暂停
                        StaticsManager.sendGameCenterDownloadStatics(mContext, file.getExt6(),
                                file.getExt7(),
                                StatGameCenterDownloadTask.ITEM_DOWNLOAD_COMPLETE_NO_PAUSE, file
                                        .getStatis().getDownloadSpeed() + "", 0, "", mid, uuid,
                                kugouid, kugouToken, clientAppid, statParams);
                    } else {// 中间有暂停
                        StaticsManager.sendGameCenterDownloadStatics(mContext, file.getExt6(),
                                file.getExt7(),
                                StatGameCenterDownloadTask.ITEM_DOWNLOAD_COMPLETE_WITH_PAUSE, file
                                        .getStatis().getDownloadSpeed() + "", 0, "", mid, uuid,
                                kugouid, kugouToken, clientAppid, statParams);
                    }

                    long id = file.getId();
                    long timestamp = System.currentTimeMillis() / 1000l;
                    DownloadOperator.getInstance().updateDownloadFinishTime(id, timestamp);
                }

                if (state == FileDownloader.PREPARE || state == FileDownloader.INTERUPT
                        || state == FileDownloader.FINISH || state == FileDownloader.CANCEL) {
                    Intent intent = DownloadHelper.createDownloadIntent(key,
                            DownloadHelper.NOTIFY_PROGRESS_CHANGED, state);
                    intent.putExtra("classId", file.getClassId());
                    mContext.sendBroadcast(intent);
                }
            }
        }

        @Override
        public void onError(DownloadFile file, int errorType) {
            String key = file.getKey();
            int classId = file.getClassId();
            if (classId == FileType.TYPE_APP_FILE) {
                Intent intent = DownloadHelper.createDownloadIntent(key,
                        DownloadHelper.NOTIFY_DOWNLOAD_ERROR, errorType);
                intent.putExtra("classId", classId);
                mContext.sendBroadcast(intent);
            }

            // 将该filehash对应的应用状态标记为需要自动下载
            DownloadHelper.setAppAutoDownloadFlag(key, 1);

            // 发送下载出错统计
            sendDownloadErrorStatics(file, errorType);
        }
    };

    /**
     * 发送下载出错统计
     * 
     * @param file
     * @param errorType
     */
    private static void sendDownloadErrorStatics(DownloadFile file, int errorType) {
        if (file == null) {
            return;
        }
        String mid = AppUtil.getKugouMID(mContext);
        String uuid = AppUtil.getKugouUUID(mContext);
        User user = UserManager.getInstance().getCurrentUserInternal();
        String kugouid = (user != null ? user.getKugouid() : "0");
        String kugouToken = (user != null ? user.getKugouToken() : "");
        long clientAppid = getAppId();
        String statParams = file.getExt10();

        int errorCode = 0;
        switch (errorType) {
        // 10:创建文件错误
            case FileDownloader.CREATE_FILE_ERROR:
                errorCode = 6;
                break;
            // 11:获取文件大小失败，在分块下载时，如果不能正确获取文件大小，会引发这个错误
            case FileDownloader.GET_FILE_SIZE_ERROR:
                errorCode = 13;
                break;
            // 12：超时
            case FileDownloader.TIMEOUT_ERROR:
                errorCode = 20;
                break;
            // 13:网络不可用
            case FileDownloader.NETWORK_ERROR:
                errorCode = 18;
                break;
            // 14:文件不存在
            case FileDownloader.FILE_NOT_FOUND:
                errorCode = 17;
                break;
            // 15:断点信息有误
            case FileDownloader.RANGE_ERROR:
                errorCode = 31;
                break;
            // 16:内容有误
            case FileDownloader.CONTENT_ERROR:
                errorCode = 15;
                break;
            // 17:文件不可读写
            case FileDownloader.FILE_ACCESS_ERROR:
                errorCode = 8;
                break;
        }
        StaticsManager.sendGameCenterDownloadStatics(mContext, file.getExt6(), file.getExt7(),
                StatGameCenterDownloadTask.ITEM_DOWNLOAD_ERROR, "0", errorCode, "", mid, uuid,
                kugouid, kugouToken, clientAppid, statParams);
    }

    public static void setContext(Context context) {
        mContext = context;
    }

    public static Context getContext() {
        return mContext;
    }

    public static BaseSDKConfig getSDKConfig() {
        return mSDKConfig;
    }

    public static int getSDKVersionCode() {
        return mSdkVersionCode;
    }

    public static String getSDKVersionName() {
        return mSdkVersionName;
    }

    public static OnPlatformEventListener getOnPlatformEventListener() {
        return mOnPlatformEventListener;
    }

    public static int getMerchantId() {
        if (mSDKConfig != null) {
            return mSDKConfig.getMerchantId();
        } else {
            return 0;
        }
    }

    public static long getAppId() {
        if (mSDKConfig != null) {
            return mSDKConfig.getAppId();
        } else {
            return 0;
        }
    }

    public static String getAppKey() {
        if (mSDKConfig != null) {
            return mSDKConfig.getAppKey();
        } else {
            return null;
        }
    }

    public static String getCode() {
        if (mSDKConfig != null) {
            return mSDKConfig.getCode();
        } else {
            return null;
        }
    }

    public static int getChannelId() {
        if (mSDKConfig != null) {
            return mSDKConfig.getChannelId();
        } else {
            return 0;
        }
    }

    public static int getGameId() {
        if (mSDKConfig != null) {
            return mSDKConfig.getGameId();
        } else {
            return 0;
        }
    }

    public static int getActivityOrientation() {
        if (mSDKConfig != null) {
            return mSDKConfig.getActivityOrientation();
        } else {
            return 0;
        }
    }

    public static boolean isFullScreen() {
        if (mSDKConfig != null) {
            return mSDKConfig.isFullScreen();
        } else {
            return true;
        }
    }

    public static boolean isNeedRestartWhenAccountChanged() {
        if (mSDKConfig != null) {
            return mSDKConfig.isNeedRestartWhenAccountChanged();
        } else {
            return true;
        }
    }

    public static boolean isNeedHidePayModule() {
        if (mSDKConfig != null) {
            return mSDKConfig.isNeedHidePayModule();
        } else {
            return false;
        }
    }

    public static boolean isNeedHideGameCenter() {
        if (mSDKConfig != null) {
            return mSDKConfig.isNeedHideGameCenter();
        } else {
            return false;
        }
    }

    public static boolean isPushMessage() {
        if (mSDKConfig != null) {
            return mSDKConfig.isPushMessage();
        } else {
            return true;
        }
    }

    public static int getGameType() {
        if (mSDKConfig != null) {
            return mSDKConfig.getGameType();
        } else {
            return BaseSDKConfig.GAME_TYPE_ONLINE;
        }
    }

    public static boolean isSupportForceUpdate() {
        if (mSDKConfig != null) {
            return mSDKConfig.isSupportForceUpdate();
        } else {
            return false;
        }
    }

    public static KGPayInfo getKGPayInfo() {
        return mKGPayInfo;
    }

    public static void setKGPayInfo(KGPayInfo payInfo) {
        SDKControler.mKGPayInfo = payInfo;
    }

    public static String getRoleName() {
        if (getKGPayInfo() == null || TextUtils.isEmpty(getKGPayInfo().getRoleName())) {
            return "";
        }

        return getKGPayInfo().getRoleName();

    }

    public static void setServerId(int serverId) {
        mServerId = serverId;
    }

    public static int getServerId() {
        if (getKGPayInfo() == null || getKGPayInfo().getServerId() <= 0) {
            if (mServerId > 0) {
                return mServerId;
            }
            return 1;
        }

        return getKGPayInfo().getServerId();
    }

    public static String createNewOrderId() {
        if (getKGPayInfo() == null || TextUtils.isEmpty(getKGPayInfo().getOrderId())) {
            return "";
        }

        return getKGPayInfo().getOrderId();
    }

    public static String getExtension1() {
        if (getKGPayInfo() == null || TextUtils.isEmpty(getKGPayInfo().getExtension1())) {
            return "";
        }

        return getKGPayInfo().getExtension1();
    }

    public static String getExtension2() {
        if (getKGPayInfo() == null || TextUtils.isEmpty(getKGPayInfo().getExtension2())) {
            return "";
        }

        return getKGPayInfo().getExtension2();
    }

    public static boolean isDebugMode() {
        return mIsDebugMode;
    }

    public static void setIsDebugMode(boolean debugMode) {
        SDKControler.mIsDebugMode = debugMode;
    }

    public static boolean isInitialize() {
        return mInitialize;
    }

    public static void release(boolean killProcess) {
        if (killProcess) {
            try {
                // 停止所有下载
                DownloadServiceUtil.stopAll();
                if (mDownloadServiceToken != null) {
                    // 取消绑定下载服务
                    DownloadServiceUtil.unbindFromService(mDownloadServiceToken);
                }
                if (mContext != null) {
                    // 停止下载服务
                    mContext.stopService(new Intent(mContext, DownloadService.class));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Process.killProcess(Process.myPid());
        }
    }

    /**
     * 进入充值中心
     */
    public static void enterRechargeCenter(Activity activity) {
        activity.startActivity(new Intent(activity, RechargeActivity.class));
    }

    /**
     * 进入充值中心（定额充值）
     * 
     * @param activity
     * @param money 充值金额
     */
    public static void enterRechargeCenter(Activity activity, int money) {
        activity.startActivity(RechargeActivity.createIntent(activity, money));
    }

    /**
     * 进入用户中心
     */
    public static void enterUserCenter(Activity activity) {
        Intent intent = new Intent(activity, UserCenterActivity.class);
        activity.startActivity(intent);
    }

    /**
     * 进入注册页面
     */
    public static void enterRegister(Activity activity) {
        Intent intent = new Intent(activity, RegisterByPhoneActivity.class);
        User user = UserManager.getInstance().getCurrentUser();
        if (user != null) {// 已经登录或进入游戏之后，进行注册的
            intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                    BaseCommonTitleFragmentActivity.FROM_AFTER_ENTER_GAME_REGISTER);
        } else {
            intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                    BaseCommonTitleFragmentActivity.FROM_BEFORE_ENTER_GAME_REGISTER);
        }
        activity.startActivity(intent);
    }

    /**
     * 进入游戏中心
     */
    public static void enterGameCenter(Activity activity) {
        activity.startActivity(new Intent(activity, GameCenterActivity.class));
    }

    /**
     * 进入礼包中心
     */
    public static void enterGiftBagCenter(Activity activity) {
        Intent intent = new Intent(activity, GiftBagActivity.class);
        activity.startActivity(intent);
    }

    /**
     * 进入游戏论坛
     */
    public static void enterGameForum(Activity activity) {
        Intent intent = new Intent(activity, GameForumActivity.class);
        activity.startActivity(intent);
    }

    /**
     * 切换账号
     * 
     * @param activity
     */
    public static void changeAccount(Activity activity) {
        Intent intent = new Intent(activity, LoginActivity.class);
        intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                BaseCommonTitleFragmentActivity.FROM_CHANGE_ACCOUNT);
        activity.startActivity(intent);
    }

    /**
     * 获取配置参数列表
     * 
     * @return
     */
    public static String getConfigParams() {
        StringBuilder sb = new StringBuilder();
        try {
            sb.append("MerchantId=" + getMerchantId()).append("\n").append("AppId=" + getAppId())
                    .append("\n").append("AppKey=" + getAppKey()).append("\n")
                    .append("Code=" + getCode()).append("\n").append("GameId=" + getGameId())
                    .append("\n").append("RoleName=" + getRoleName()).append("\n")
                    .append("Extendsion1=" + getExtension1()).append("\n")
                    .append("Extendsion2=" + getExtension2()).append("\n")
                    .append("OrderId=" + createNewOrderId()).append("\n")
                    .append("GameType=" + getGameType()).append("\n")
                    .append("PushMessage=" + isPushMessage()).append("\n")
                    .append("isSupportForceUpdate=" + isSupportForceUpdate()).append("\n")
                    .append("ChannelId=" + getChannelId()).append("\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static void activityCreate() {
        mActivityCounter++;
    }

    public static void activityDestory() {
        mActivityCounter--;
    }

    public static int getActivityCounter() {
        return mActivityCounter;
    }

    /**
     * 接口Url是否线上正式环境
     * 
     * @return true是 false否
     */
    public static boolean isOnlineOfficial() {
        return UrlWrapper.SERVER_HOST.contains("sdk2.sy.kugou.com");
    }
}
